package io.chenglicun.modules.bus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.chenglicun.common.page.PageData;
import io.chenglicun.common.service.impl.BaseServiceImpl;
import io.chenglicun.common.user.UserDetail;
import io.chenglicun.common.utils.ConvertUtils;
import io.chenglicun.modules.bus.dao.BusMomentDao;
import io.chenglicun.modules.bus.dto.BusMomentDTO;
import io.chenglicun.modules.bus.entity.BusMomentEntity;
import io.chenglicun.modules.bus.service.BusMomentService;
import io.chenglicun.modules.security.user.SecurityUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 业务_村民留言版/乡情圈
 *
 * @author LYB jssqsylyb@163.com
 * @since 1.0 2023-09-05
 */
@Service
public class BusMomentServiceImpl extends BaseServiceImpl<BusMomentDao, BusMomentEntity> implements BusMomentService {

    @Override
    public PageData<BusMomentDTO> page(Map<String, Object> params) {
        paramsToLike(params, "creator");
        //查询当前用户是否点赞
        UserDetail user = SecurityUser.getUser();
        params.put("userId",user.getId());
        IPage<BusMomentDTO> page = getPage2(params, "create_date", false);
        List<BusMomentDTO> list = baseDao.getList(params);

        return getPageData(list, page.getTotal(), BusMomentDTO.class);

    }

    @Override
    public BusMomentDTO get(Long id) {
        BusMomentEntity entity = baseDao.selectById(id);

        return ConvertUtils.sourceToTarget(entity, BusMomentDTO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(BusMomentDTO dto) {
        if (StringUtils.isNotBlank(dto.getReplyContent())&&dto.getReplyUser()==null){
            UserDetail user = SecurityUser.getUser();
            dto.setReplyTime(new Date());
            dto.setReplyUser(user.getId());
        }

        BusMomentEntity entity = ConvertUtils.sourceToTarget(dto, BusMomentEntity.class);

        insert(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(BusMomentDTO dto) {
        if (StringUtils.isNotBlank(dto.getReplyContent())&&dto.getReplyUser()==null){
            UserDetail user = SecurityUser.getUser();
            dto.setReplyTime(new Date());
            dto.setReplyUser(user.getId());
        }

        BusMomentEntity entity = ConvertUtils.sourceToTarget(dto, BusMomentEntity.class);

        updateById(entity);
    }

    @Override
    public void delete(Long[] ids) {
        deleteBatchIds(Arrays.asList(ids));
    }

    @Override
    public List<BusMomentDTO> list(Map<String, Object> params) {
        paramsToLike(params, "creator");
        List<BusMomentDTO> list = baseDao.getList(params);
        return list;
    }
}